<?php

/*
*/

class Right_Control_model extends CI_Model
{

	function __construct()
	{
		parent::__construct();

		//选择数据库
		$this->load->library('test_database');
		$this->test_database->test();
		$this->load->database($this->test_database->get_db());

		//载入模型
		$this->load->model('User_Right_model');
	}

	/***
	For private function here
	***/
	private function check_right($user_rights, $controller_right)
	{
		try {
			$controller_right = explode('.', $controller_right);
			if (1 == count($controller_right))
			{
				foreach ($user_rights as $user_right)
				{
					if ($controller_right[0] == $user_right['class_name'])
					{
						return TRUE;
					}
					$this->error = 'RIGHT_ERR';
				}
			}
			else if (2 == count($controller_right))
			{
				foreach ($user_rights as $user_right)
				{
					if ($controller_right[0].$controller_right[1] == $user_right['class_name'].$user_right['function_name'])
					{
						return TRUE;
					}
				}
				$this->error = 'RIGHT_ERR';
			}
			else
			{
				$this->error = 'RIGHT_ERR';
			}
		} catch (Exception $e) {
			$this->error = 'SYS_ERR';
		}
		return FALSE;
	}

	/***
	For public function here
	***/

	//验证用户权限
	public function check($user_id, $controller_right)
	{
		if ($this->User_Right_model->get_rights($user_id))
		{
			$user_rights = $this->User_Right_model->rights();
			if (!empty($user_rights))
			{
				if ($this->check_right($user_rights, $controller_right))
				{
					return TRUE;
				}
				else
				{
					$this->error = '没有权限';
				}
			}
			else
			{
				$this->error = '用户没有分配权限';
			}
		}
		else
		{
			$this->error = $this->User_Right_model->error;
		}
		return FALSE;
	}

}